import fs from "fs-extra";
import path from "path";

function getRoot() {
  return path.join(process.cwd(), "./");
}

export function configValue(mode) {
  let configStr = fs.readFileSync(
    path.join(process.cwd(), `.env.${mode}`),
    "utf-8"
  );
  let obj = {};
  configStr.split("\n").forEach((line) => {
    let [key, value] = line.split("=");
    if (key && value) {
      value = value.replaceAll(/'|"/g, "");
      obj[key] = value;
    }
  });
  return obj;
}

function writeConfig() {
  //暂时不做判断，在编辑命令时看是否需要执行这里的脚本
  //   let command = process.env.npm_lifecycle_event;

  fs.mkdirp(path.join(getRoot(), "dist"));
  let value = configValue("production");
  let configName = value["VITE_ENV_CONFIG_NAME"] || "__ENV_CONFIG__";
  let scriptStr = `
  window.${configName}=${JSON.stringify(value)}
  Object.freeze(${configName});
      Object.defineProperty(window, "${configName}", {
        configurable: false,
        writable: false,
      });
    `;

  fs.writeFileSync(path.join(getRoot(), "dist", "APP_CONFIG.js"), scriptStr);
}

writeConfig();
